<?php
header("Content-Type: text/html;charset=utf-8");
header("Cache-Control:no-cache,must-revalidate,no-store");
header("Pragma:no-cache");
header("Expires:-1");

$code = $_GET['code'];//前端传来的code值
$appid = "wx1be0fcc87e8da9c0";
$appsecret = "fd39f579d5ef78908ee3249ec5a8a027";//获取openid
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
$result = https_request($url);
// print_r($result);
// echo "<br />";
$jsoninfo = json_decode($result, true);
// print_r($jsoninfo);
// echo "<br />";
$openid = $jsoninfo["openid"];//从返回json结果中读出openid
$access_token = $jsoninfo["access_token"];//从返回json结果中读出openid
// $callback=$_GET['callback'];  // echo $callback."({result:'".$openid."'})";

$url1 = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$result1 = https_request($url1);
$jsoninfo1 = json_decode($result1, true);
$nickname=$jsoninfo1["nickname"];
if(!isset($jsoninfo1["nickname"])){
    //未授权，跳转
    header("location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1be0fcc87e8da9c0&redirect_uri=http://test2015.embayun.com/oauth2.php&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
    exit();
}
echo "获取的用户信息：<br />";
echo "openid：".$openid;
echo "<br />";
echo "微信昵称：".$nickname;
echo "<br />";
echo "unionid：".$jsoninfo1["unionid"];
echo "<br />";
echo "<img src=\"".$jsoninfo1["headimgurl"]."\" width=\"320\" height=\"320\" >";
echo "<br />";
echo "其它信息：";
echo "<br />";
print_r($jsoninfo1);
echo "<br />";
// echo $openid.":".$access_token.":".$nickname; //把openid 送回前端

 function https_request($url,$data = null){
  $curl = curl_init();   
  curl_setopt($curl, CURLOPT_URL, $url);   
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);   
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);    
  if (!empty($data)){    
  curl_setopt($curl, CURLOPT_POST, 1);  
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);   
  }    
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
  $output = curl_exec($curl);    
  curl_close($curl);    
  return $output;
 }

